from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from database import get_db
from models import SystemConfig, Question, Conversation
from schemas import QuestionResponse, QuestionListResponse, ConversationResponse, ConversationListResponse
from logger import logging

router = APIRouter(
    prefix="/api/external",
    tags=["外部系统接口"],
)


@router.get("/floor-guide", summary="获取楼层导览图片URL")
async def get_floor_guide_image(
    db: Session = Depends(get_db)
):
    """
    获取配置中的楼层导览图片URL地址（无需认证）
    返回楼层导览图片的完整URL路径，如果未配置则返回空字符串
    """
    try:
        # 查询系统配置
        config = db.query(SystemConfig).first()

        if not config or not config.floor_guide_image:
            logging.warning("楼层导览图片未配置")
            return {
                "floor_guide_image": "",
                "message": "楼层导览图片未配置"
            }
        
        return {
            "floor_guide_image": config.floor_guide_image,
            "message": "获取成功"
        }

    except Exception as e:
        logging.error(f"获取楼层导览图片失败: {str(e)}")
        raise HTTPException(
            status_code=500,
            detail=f"获取楼层导览图片失败: {str(e)}"
        )


@router.get("/questions", response_model=QuestionListResponse, summary="获取开放状态的问题")
async def get_active_questions(
    db: Session = Depends(get_db)
):
    """
    获取开放状态(active)的问题列表（无需认证）
    返回所有状态为active的问题，按使用次数降序排列
    """
    try:
        # 构建查询 - 只查询状态为active的问题
        query = db.query(Question).filter(Question.status == "active")

        # 获取总数
        total = query.count()

        # 分页并按使用次数降序排列
        questions = query.order_by(
            Question.usage_count.desc(),
            Question.id.desc()
        ).all()

        logging.info(f"外部系统获取开放问题列表，共 {total} 条记录")

        return QuestionListResponse(
            total=total,
            questions=[QuestionResponse.model_validate(q) for q in questions]
        )

    except Exception as e:
        logging.error(f"获取开放问题列表失败: {str(e)}")
        raise HTTPException(
            status_code=500,
            detail=f"获取开放问题列表失败: {str(e)}"
        )


@router.get("/conversations", response_model=ConversationListResponse, summary="获取外部系统的历史记录")
async def get_external_conversations(
    db: Session = Depends(get_db)
):
    """
    获取外部系统的历史对话记录（无需认证）
    只返回source字段为external的对话记录，按更新时间降序排列
    """
    try:
        # 构建查询 - 只查询来源为external的对话
        query = db.query(Conversation).filter(
            Conversation.source == "external")

        # 获取总记录数
        total = query.count()

        # 按更新时间降序排列，并进行分页
        conversations = query.order_by(
            Conversation.updated_at.desc()
        ).all()

        logging.info(f"外部系统查询历史对话列表，总计 {total} 条记录")

        return ConversationListResponse(
            total=total,
            conversations=conversations
        )

    except HTTPException:
        raise
    except Exception as e:
        logging.error(f"获取外部系统历史对话列表失败: {str(e)}")
        raise HTTPException(
            status_code=500,
            detail=f"获取外部系统历史对话列表失败: {str(e)}"
        )


@router.get("/conversations/{conversation_id}", response_model=ConversationResponse, summary="获取外部系统对话详情")
async def get_external_conversation(
    conversation_id: int,
    db: Session = Depends(get_db)
):
    """
    获取外部系统的对话历史详情（无需认证）

    - **conversation_id**: 对话记录的ID

    只返回source字段为external的对话记录详情
    """
    try:
        # 查询指定ID且来源为external的对话
        conversation = db.query(Conversation).filter(
            Conversation.id == conversation_id,
            Conversation.source == "external"
        ).first()

        if not conversation:
            raise HTTPException(
                status_code=404,
                detail=f"外部系统对话记录 ID {conversation_id} 不存在"
            )

        logging.info(f"外部系统获取对话详情 ID: {conversation_id}")

        return ConversationResponse.model_validate(conversation)

    except HTTPException:
        raise
    except Exception as e:
        logging.error(f"获取外部系统对话详情失败: {str(e)}")
        raise HTTPException(
            status_code=500,
            detail=f"获取外部系统对话详情失败: {str(e)}"
        )
